package com.njit.postbar;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.njit.postbar.model.Dynamic;
import com.njit.postbar.model.User;
import com.njit.postbar.utils.Remove;

import org.litepal.LitePal;

import java.util.Date;
/**
 *@author yuruiqiao
 *@date 2020/6/6
 *@description 动态的添加和修改
 */
public class Post extends Activity {

    private Dynamic dynamic;
    private User user;
    private EditText title,circle,content;
    private Button postBtn,updateBtn;
    private String titleText,circleText,contentText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.post);
        Remove.removeTop(this);
        init();
        //添加一条动态
        postBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(checkInfo()){
                    insertDynamic();
                    Toast.makeText(getBaseContext(),"上传成功!", Toast.LENGTH_LONG).show();
                    finish();
                }
            }
        });

        //修改一条动态
        updateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(checkInfo()){
                    updateDynamic(dynamic.getId(),user.getId());
                    Toast.makeText(getBaseContext(),"修改成功!", Toast.LENGTH_LONG).show();
                    finish();
                }
            }
        });

        //选择一个圈子
        circle.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    Intent intent = new Intent();
                    intent.putExtra("callback",true);
                    intent.setClass(Post.this,Search.class);
                    startActivityForResult(intent, 0x11);
                    circle.clearFocus();
                }
            }
        });


    }
    /**
     *@author yuruiqiao
     *@date 2020/6/4
     *@description 初始化
     */
    public void init(){
        //用户信息
        Intent intent = this.getIntent();
        user = (User) intent.getSerializableExtra("user");
        dynamic = (Dynamic) intent.getSerializableExtra("dynamic");

        title = findViewById(R.id.post_title);
        circle = findViewById(R.id.post_circle);
        content = findViewById(R.id.post_content);
        postBtn = findViewById(R.id.post_button);
        updateBtn = findViewById(R.id.post_update);
        //一个页面两个作用,添加或者修改,如果dynamic已经存在,说明要修改,否则是添加
        if(dynamic != null){
            updateBtn.setVisibility(View.VISIBLE);
        }else{
            postBtn.setVisibility(View.VISIBLE);
        }
    }
    /**
     *@author yuruiqiao
     *@date 2020/6/4
     *@description 插入一条动态
     */
    private void insertDynamic(){
        Dynamic dynamic = new Dynamic();
        dynamic.setTitle(titleText);
        dynamic.setCircle(circleText);
        dynamic.setContent(contentText);
        dynamic.setPreviewImageUrl(getImageUrl(contentText));
        dynamic.setUserId(user.getId());
        dynamic.setLikeNumber(0);
        dynamic.setStarNumber(0);
        dynamic.setCommentNumber(0);
        dynamic.setCreateTime(new Date());
        dynamic.save();
    }
    /**
     *@author yuruiqiao
     *@date 2020/6/6
     *@description 修改一条动态
     */
    private void updateDynamic(int dynamicId,int userId){
        Dynamic dynamic = LitePal.where("id = ?",dynamicId+"").find(Dynamic.class).get(0);
        //判断是否为自己发布的动态
        if(dynamic.getUserId().equals(userId)){
            dynamic.setTitle(titleText);
            dynamic.setCircle(circleText);
            dynamic.setContent(contentText);
            dynamic.setUpdateTime(new Date());
            dynamic.setPreviewImageUrl(getImageUrl(contentText));
            dynamic.save();
            Toast.makeText(getBaseContext(),"修改成功!", Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(getBaseContext(),"修改失败!", Toast.LENGTH_LONG).show();
        }
    }
    /**
     *@author yuruiqiao
     *@date 2020/6/6
     *@description 获取字符串中的图片地址
     */
    public String getImageUrl(String contentText){
        if(contentText.length()>5){
            int imageBegin = contentText.indexOf("![](") + 4;
            int imageEnd = imageBegin + contentText.substring(imageBegin + 1).indexOf(")") + 1;
            String str = contentText.substring(imageBegin, imageEnd);
            if("http://".equals(str.substring(0,7))){
                return contentText.substring(imageBegin, imageEnd);
            }
        }
        return "";
    }
    /**
     *@author yuruiqiao
     *@date 2020/6/6
     *@description 最基础的容错判断
     */
    public boolean checkInfo(){
        titleText = title.getText().toString();
        circleText = circle.getText().toString();
        contentText = content.getText().toString();
        if(user == null){
            Toast.makeText(getBaseContext(),"请先登录", Toast.LENGTH_LONG).show();
        }else if("".equals(titleText)){
            Toast.makeText(getBaseContext(),"标题不能为空", Toast.LENGTH_LONG).show();
        }else if("".equals(circleText)){
            Toast.makeText(getBaseContext(),"圈子不能为空", Toast.LENGTH_LONG).show();
        }else if("".equals(contentText)){
            Toast.makeText(getBaseContext(),"内容不能为空", Toast.LENGTH_LONG).show();
        }else {
            return true;
        }
        return false;
    }
    //回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==0x11) {
            if (resultCode==RESULT_OK) {
                String sData = data.getStringExtra("circleName");
                circle.setText(sData);
            }
        }
    }
}
